<?php
/**
 * Created by PhpStorm.
 * User: mr_lee
 * Date: 2017/10/17
 * Time: 上午11:25
 */

namespace app\index\controller;
use app\common\model\Agent;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\WxOpen;
use think\Controller;
use Wechat\Wxobjopen;

class Wxauths extends Controller
{

    public function agentauths(){
        $request = request();
        $param = $request->param();
        $url = url('wxauths/agentauth',['id'=>$param['id']]);
        echo '<a href='.$url.'><img style="width:300px;height:100px" src="https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon_button3_1.png"/></a>';
    }

    //获取代理商授权
    public function agentauth()
    {
        $request = request();
        $param = $request->param();
        if (!isset($param['id'])){
            die('非法访问');
        }
        $Agent=new Agent();
        $config=$Agent->where(array('id'=>$param['id']))->find();
        if ($config['wx_open_id']){
            die('请勿重复授权');
        }

        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],

        );;
        $weObj = new Wxobjopen($options);
        $pre_auth_code = $weObj->get_pre_auth_code();
        if (!$request->get('auth_code')) {
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $callback = $http_type . $_SERVER['HTTP_HOST'] . url("wxauths/agentauth", $param);
            $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" . $config['component_appid'] . "&pre_auth_code=" . $pre_auth_code . "&redirect_uri=" . $callback;
            header("Location: $url");
            exit();
        } else {
            $appinfo = $weObj->authorization_info($request->get('auth_code'));
            $auth_appid = $appinfo['authorization_info']['authorizer_appid'];
            $auther['component_appid'] = $config['component_appid'];
            $auther['authorizer_appid'] = $auth_appid;
            $auther_info = $weObj->get_auther_info($auther);
            if ($auther_info['authorizer_info']['service_type_info']['id'] == 2 && ($auther_info['authorizer_info']['verify_type_info']['id'] == 0 || $auther_info['authorizer_info']['verify_type_info']['id'] == 3)) {
                $data['gh_nick_name'] = $auther_info['authorizer_info']['nick_name'];
                $data['service_type_info'] = $auther_info['authorizer_info']['service_type_info']['id'];
                $data['verify_type_info'] = $auther_info['authorizer_info']['verify_type_info']['id'];
                $data['gh_id'] = $auther_info['authorizer_info']['user_name'];
                $data['alias'] = $auther_info['authorizer_info']['alias'];
                $data['qrcode_url'] = $auther_info['authorizer_info']['qrcode_url'];
                $data['principal_name'] = $auther_info['authorizer_info']['principal_name'];
                $data['wx_open_info'] = json_encode($auther_info, JSON_UNESCAPED_UNICODE);
                $data['authorizer_appid'] = $auth_appid;
                $data['authorizer_refresh_token'] = $appinfo['authorization_info']['authorizer_refresh_token'];
                $data['at_access_token'] = $appinfo['authorization_info']['authorizer_access_token'];
                $data['at_addtime'] = time();
                $data['at_expires_in'] = 7000;
                $data['addtime'] = time();
                $data['zt'] = 1;
                $func_info = "";
                foreach ($appinfo['authorization_info']['func_info'] as $k => $v) {
                    $func_info .= $v['funcscope_category']['id'] . ',';
                }
                $WxOpen = new WxOpen();
                $data['func_info'] = $func_info;
                $wx_open = $WxOpen->where(array('authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']))->find();
                if ($wx_open) {
                    $sj = $WxOpen->save($data, ['authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']]);
                    $da2['wx_open_id'] = $wx_open['id'];
                } else {
                    $sj = $WxOpen->save($data);
                    $da2['wx_open_id'] = $WxOpen->id;
                }
                $da2['auth_type'] = 1;

                $mss['id'] = $param['id'];
                $Agent = new Agent();
                $Agent->where($mss)->update($da2);
                if ($sj) {
                    die('授权成功，请关闭此页面');
                } else {
                    die('授权失败，请重新授权');
                }
            } else {
                $this->error('该公众号为订阅号或者未通过微信认证，请确认后重新授权');
            }

        }
    }

    public function momachauths(){
        $request = request();
        $param = $request->param();
        $url = url('wxauths/momachauth',['id'=>$param['id']]);
        echo '<a href='.$url.'><img style="width:300px;height:100px" src="https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon_button3_1.png"/></a>';
    }

    public function momachauth()
    {
        $request = request();
        $param = $request->param();
        if (!isset($param['id'])){
            die('非法访问');
        }
        $Momerchant = new Momerchant();
        $momachinfo=$Momerchant->where(array('id'=>$param['id']))->find();
        if ($momachinfo['wx_open_id']){
            die('请勿重复授权');
        }
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';




        $Momerchant = new Momerchant();
        $agent=$Momerchant->where(array('id'=> $param['id']))->value('agent');
        $Agent=new Agent();
        $config=$Agent->where(array('id'=>$agent))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
        );
        $weObj = new Wxobjopen($options);
        $pre_auth_code = $weObj->get_pre_auth_code();

        if (!$request->get('auth_code')) {
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $callback = $http_type . $_SERVER['HTTP_HOST'] . url("wxauths/momachauth", $param);
            $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" . $config['component_appid'] . "&pre_auth_code=" . $pre_auth_code . "&redirect_uri=" . $callback;
            header("Location: $url");
            exit();
        } else {
            $appinfo = $weObj->authorization_info($request->get('auth_code'));
            $auth_appid = $appinfo['authorization_info']['authorizer_appid'];
            $auther['component_appid'] = $config['component_appid'];
            $auther['authorizer_appid'] = $auth_appid;
            $auther_info = $weObj->get_auther_info($auther);
            if ($request->param('auth_action') == "xcx") {
                if (!isset($auther_info['authorizer_info']['MiniProgramInfo'])){
                    die('请授权类型为微信小程序');
                }
                $data['auth_action'] = 1;
            } else {
                if (isset($auther_info['authorizer_info']['MiniProgramInfo'])){

                    die('请授权类型为微信公众号');
                }
                $data['auth_action'] = 0;
            }
            if ($request->param('auth_action') == "xcx" || ($auther_info['authorizer_info']['service_type_info']['id'] == 2 && ($auther_info['authorizer_info']['verify_type_info']['id'] == 0 || $auther_info['authorizer_info']['verify_type_info']['id'] == 3))) {
                $data['gh_nick_name'] = $auther_info['authorizer_info']['nick_name'];
                $data['service_type_info'] = $auther_info['authorizer_info']['service_type_info']['id'];
                $data['verify_type_info'] = $auther_info['authorizer_info']['verify_type_info']['id'];
                $data['gh_id'] = $auther_info['authorizer_info']['user_name'];
                $data['alias'] = $auther_info['authorizer_info']['alias'];
                $data['qrcode_url'] = $auther_info['authorizer_info']['qrcode_url'];
                $data['principal_name'] = $auther_info['authorizer_info']['principal_name'];
                $data['wx_open_info'] = json_encode($auther_info, JSON_UNESCAPED_UNICODE);
                $data['authorizer_appid'] = $auth_appid;
                $data['authorizer_refresh_token'] = $appinfo['authorization_info']['authorizer_refresh_token'];
                $data['at_access_token'] = $appinfo['authorization_info']['authorizer_access_token'];
                $data['at_addtime'] = time();
                $data['at_expires_in'] = 7000;
                $data['addtime'] = time();
                $data['zt'] = 1;
                $func_info = "";
                foreach ($appinfo['authorization_info']['func_info'] as $k => $v) {
                    $func_info .= $v['funcscope_category']['id'] . ',';
                }
                $WxOpen = new WxOpen();
                $data['func_info'] = $func_info;
                $wx_open = $WxOpen->where(array('authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']))->find();

                if ($wx_open) {
                    $sj = $WxOpen->save($data, ['authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']]);
                    if ($request->param('auth_action') == "xcx") {
                        $da2['wx_open_id_xcx'] = $wx_open['id'];
                    } else {
                        $da2['wx_open_id'] = $wx_open['id'];
                    }
                } else {
                    $sj = $WxOpen->save($data);
                    if ($request->param('auth_action') == "xcx") {
                        $da2['wx_open_id_xcx'] = $WxOpen->id;
                    } else {
                        $da2['wx_open_id'] = $WxOpen->id;
                    }
                }
                $da2['auth_type'] = 1;
                $mss['id'] = $param['id'];
                $Momerchant = new Momerchant();
                $Momerchant->save($da2, $mss);
                //  end

                $mapss['top_mid'] = $mss['id'];
                $da3 = $da2;
                $Merchant = new Merchant();
                $Merchant->allowField(true)->save($da3,$mapss);

                if ($sj) {
                    die('授权成功，请关闭此页面');
                } else {
                    die('授权失败，请勿重新授权');
                }
            } else {
                die('该公众号为订阅号或者未通过微信认证，请确认后重新授权');
            }
        }

    }


}